#include "mat_ui_gameover.h"
#include "mat_gamerule.h"
#include "mat_scoring.h"
#include "ui/ui_flexeffect.h"
#include "mat_ui_msgbox.h"
#include "mat_ui_achievement.h"
#include "mat_level_manager.h"
#include "mat_mapstate.h"
#include "mat_animation_mgr.h"
#include "mat_ui_helper.h"
#include "mat_sfx_manager.h"
#include "gen_game_state.h"

#include "admanager/admanager.h"
#include "nextpeer/np_manager.h"
#include "gameflow/game_flow_manager.h"
#include "gameflow/ui_popup.h"
#include "application/game_application.h"
#include "application/game_rms.h"
#include "lang/lang.h"

static MATUIGameOver* g_Instance;

bool	RenderMe()
{
	g_Instance->Render();
	return true;
}


MATUIGameOver::MATUIGameOver() : 
					MATUIPopupAnimator("ui/gameover.ui",""),				
					m_pUIPostFB(NULL),										
					m_pUIFlexEffect(NULL),					
					m_pButtonNext(NULL),
					m_pButtonRetry(NULL),
					m_AlphaGlow(0),
					m_GlowAddVal(1)
{
	g_Instance = this;

	
	//m_ObjTurns.Load("img/score_number.lua",math::Vec2(0.5f,0.8f));

	if(m_pPopup)
	{
		
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("StarGray_1"));
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("StarGray_2"));
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("StarGray_3"));
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("Star_1"));
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("Star_2"));
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("Star_3"));
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("LabelYouFail"));

		//MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("button_glow"));
		//MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("button_play"));
		//MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("button_retry"));
		//MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("button_next"));
		


		m_pAnimateWidget = m_pPopup->GetWidget("background");
		m_pUIPostFB = m_pPopup->GetWidget("post_fb");
		if(m_pUIPostFB)
			m_pUIPostFB->SetIsVisible(false);
		
		MATUIPopupAnimatorMgr::Instance().AddPopupAnimator(MATUIPopupAnimatorMgr::POPUP_NAMES_GAMEOVER,this);

		m_Type = ANIMATION_SLIDEFROMTOP;
		m_pPopup->SetWidgetFunctor("button_play",UI_DELEGATE(MATUIGameOver, OnButtonPlay));

	
		m_pUIFlexEffect = (ui::UIFlexEffect*)m_pPopup->GetWidget("scorerender");

		if(m_pUIFlexEffect)
			m_pUIFlexEffect->SetRenderFunc((ui::UIFlexEffect::FLEXEFFECT_RENDERFUNCTION)RenderMe);

		m_pButtonNext = m_pPopup->GetWidget("button_next");		
		m_pButtonRetry = m_pPopup->GetWidget("button_retry");
		m_pUIYouFailed = m_pPopup->GetWidget("LabelYouFail");
		m_pUIStarsFrame = m_pPopup->GetWidget("stars_frame");
		m_pUILevelText = m_pPopup->GetWidget("level_txt");
		m_pUIReason = m_pPopup->GetWidget("reason_txt");
		m_pUIButtonGlow = m_pPopup->GetWidget("button_glow");

		m_ObjScore.Load("ui_img/time_number.lua", m_pPopup->GetWidget("score") );

		char	Buffer[256];
		
		for(int i = 0; i < STAR_COUNT; i++)
		{
			sprintf(Buffer, "Star_%i", i+1);
			m_pUIStars[i] = m_pPopup->GetWidget(Buffer);
			m_StarPos[i] = m_pUIStars[i]->GetPosition(); 
		}
		
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("button_play"));
		MATUIHelper::ResizeToCurentAspectRatio(m_pPopup->GetWidget("button_glow"));
		
        m_pButtons.push_back(new MATUIHelper(m_pPopup->GetWidget("button_next")));	
		m_pButtons.push_back(new MATUIHelper(m_pPopup->GetWidget("button_retry")));	
	}
}

MATUIGameOver::~MATUIGameOver()
{
	for(int i = 0; i < (int)m_pButtons.size(); i++)
	{
		UTIL_SAFE_DELETE(m_pButtons[i]);
	}
	m_pButtons.resize(0);
}


void					MATUIGameOver::Show()
{
	const bool IsLevelSuccess = MATLevelManager::Instance().IsLevelSuccess();	

	if(m_pPopup->IsActive())
		return;

	NextPeerManager::Instance().ReportControlledTournamentOver(MATScoring::Instance().GetScoreValue());
	char	Buffer[256];

	for(int i = 0; i < STAR_COUNT; i++)
	{
		if(m_pUIStars[i])
			m_pUIStars[i]->SetIsVisible(false);
	
	}

	m_Score = MATScoring::Instance().GetScoreValue();		

	
	m_ObjScore.InitValue(MATScoring::Instance().GetScoreValue());
	m_Delay = 0.6f;

		
	if(m_pUIPostFB)
	{		
		MATUIAnimator::Instance().Add(	m_pUIPostFB,
									MATAnimatedUI::ANIMATE_STYLE_POPPINGUP,
									2.0f,NULL);
	}

	

	const int LevelNumber =  MATLevelManager::Instance().GetCurrentLevel();
	sprintf(Buffer, "Level: %i", LevelNumber);
	m_pUILevelText->SetTextA(Buffer);

	if(IsLevelSuccess)
	{
		int StarGot = MATLevelManager::Instance().GetStarCount();
		MATSfx* pSfx;
		for(int i = 0; i < StarGot; i++)
		{
			if(m_pUIStars[i])
				MATUIAnimator::Instance().Add(	m_pUIStars[i],
												MATAnimatedUI::ANIMATE_STYLE_STAMP,
												1.0f + (0.5f * i) ,NULL);	

			if(StarGot == 3)
			{
				pSfx = MATSFXManager::Instance().Spawn( MATSfx::SFX_GOT_3STARS, m_StarPos[i],1.0f,0,false,MATSounds::SFX_NONE);		
				pSfx->SetDelay(2.5f);
				pSfx->SetSFX(MATSounds::SFX_LEVEL_FULLSTAR);
				pSfx->SetIsPostRender(true);
			}
			
		}
		MATSounds::Instance().PlaySoundSFX(MATSounds::SFX_LEVEL_SUCCESS);
		m_PreviousLevelStatus = g_pApp->GetRMS()->IsOpen(LevelNumber);
		const int CurrentLevelInt = MATLevelManager::Instance().GetStarCount() + 2;
		if( CurrentLevelInt > m_PreviousLevelStatus )
		{
			g_pApp->GetRMS()->SetOpen(LevelNumber , CurrentLevelInt );
			if(g_pApp->GetRMS()->IsOpen(LevelNumber+1) == 0)
				g_pApp->GetRMS()->SetOpen(LevelNumber+1 , 1);
			g_pApp->GetRMS()->Save();
		}
	}
	else
	{
		MATSounds::Instance().PlaySoundSFX(MATSounds::SFX_LEVEL_FAIL);
	}
	
	if(m_pButtonNext)
		m_pButtonNext->SetIsVisible(IsLevelSuccess);

	if(m_pUIStarsFrame)
		m_pUIStarsFrame->SetIsVisible(IsLevelSuccess);

	if(m_pButtonRetry)
		m_pButtonRetry->SetIsVisible(!IsLevelSuccess);

	if(m_pUIYouFailed)
		m_pUIYouFailed->SetIsVisible(!IsLevelSuccess);

	if(m_pUIReason)
	{
		if(IsLevelSuccess)
			m_pUIReason->SetTextA("");
		else
			m_pUIReason->SetTextA(MATLevelManager::Instance().GetFailReason());
	}

	

	MATUIPopupAnimator::Show();
}

void					MATUIGameOver::Render()
{
	m_ObjScore.Render(GENGameState::GetGame()->GetGameMatch5()->GetScale());
	//m_ObjTurns.Render(0.5f);

	
}


void					MATUIGameOver::Tick(float dt)
{
	if(!m_pPopup->IsActive())
		return;
	
	if(m_Delay > 0)
	{
		m_Delay -= dt;
		return;
	}

	m_ObjScore.Tick(dt);
	
	for(int i = 0; i < (int)m_pButtons.size(); i++)
	{
		m_pButtons[i]->Tick(dt);
	}

	m_AlphaGlow += ( (float)m_GlowAddVal * dt);
	if(m_AlphaGlow > 1.0f)
	{
		m_GlowAddVal = -1;
		m_AlphaGlow = 1.0f;
	}

	if(m_AlphaGlow < 0.0f)
	{
		m_GlowAddVal = 1;
		m_AlphaGlow = 0.0f;
	}

	if(m_pUIButtonGlow)
		m_pUIButtonGlow->SetColor(1.0f,1.0f,1.0f,m_AlphaGlow);

	

		

}

void DELEGATE_CALL		MATUIGameOver::OnButtonPlay(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
	OnPressPlay();
	

}


void	MATUIGameOver::OnPressPlay()
{
	Hide();
	MATUIAnimator::Instance().Add(m_pAnimateWidget,MATAnimatedUI::ANIMATE_STYLE_HIDE_TOTOP,0, this);

	if( MATLevelManager::Instance().IsLevelSuccess())
	{

		if(MATLevelManager::Instance().GetCurrentLevel() == LEVEL_LAST)
		{
			gameflow::GameFlowManager::Instance().SetTransitionEffect("fade","MainMenu","",NULL);
			MATUIPopupAnimator* pPopup = MATUIPopupAnimatorMgr::Instance().GetPopup(MATUIPopupAnimatorMgr::POPUP_NAMES_MSGBOX);
			((MATUIMsgBox*)pPopup)->ShowExtra(0.01f, "Congratulation! You have completed all the levels! ^_^" , 
												MATUIMsgBox::ACTION_NONE);			
			return;
		}


		MATLogicBoard::Instance().Clear();
		gameflow::GameFlowManager&	Game = gameflow::GameFlowManager::Instance();
		MATMapState* pMapState = (MATMapState*) Game.GetStateByName("map");
		Game.TransitionToState("map",1.0f);
        //Game.SetTransitionEffect("fade","map","",NULL);
		pMapState->GoToNextWayPoint(m_PreviousLevelStatus, MATLevelManager::Instance().GetStarCount());
	}
}

void					MATUIGameOver::OnAnimatedUIFinish()
{
	
	if(m_pPopup)
		m_pPopup->Hide(NULL);

	if(m_pUIPostFB)
		m_pUIPostFB->SetIsVisible(false);
	
	if( MATLevelManager::Instance().IsLevelSuccess())
	{
		// go to map
	}
	else
	{
		MATAnimationManager::Instance().ForceFinish();
		MATLevelManager::Instance().ReplayLevel();
	}

    AdManager::Instance().RequestFullScreenAd(1);  

	
}

bool	MATUIGameOver::KeyPressed(input::Keyboard::KEY* pKey)
{
	if(m_pPopup->IsActive() && pKey->KeyID == KEY_ESCAPE)
	{
		OnPressPlay();
		return true;
	}
	return false;
}




